import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:giwiki/entities/entities.dart';
import 'package:giwiki/entities/entities_data.dart';
import 'package:giwiki/screens/settings.dart';

import 'character_detail_screen.dart';

class CharactersScreen extends StatefulWidget {
  const CharactersScreen({super.key});

  @override
  State<CharactersScreen> createState() => _CharactersScreenState();
}

class _CharactersScreenState extends State<CharactersScreen> {
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    columnCountSettingChanged.subscribe(_setState);
  }

  @override
  void dispose() {
    columnCountSettingChanged.unsubscribe(_setState);
    _scrollController.dispose();
    super.dispose();
  }

  _setState(_) {
    setState(() {});
  }

  final _img = randomCardImage();

  @override
  Widget build(BuildContext context) {
    var rat = 1080.0 / 1920.0 / 3;
    var size = MediaQuery.of(context).size;
    var sw = min(size.width, size.height);
    var sh = max(size.width, size.height);
    int columnInt = 2;
    if (columnCountSetting != 0) {
      columnInt = columnCountSetting;
    } else {
      var column = sw / sh / rat;
      var columnInt = column.floor();
      if (columnInt == 0) {
        columnInt = 1;
      }
    }
    var w = sw / (columnInt + 0.3);
    var characterWrapsList = characterWraps(w, columnInt);
    var list = ListView(
      controller: _scrollController,
      children: [
        Container(height: w / 10),
        Wrap(
          alignment: WrapAlignment.spaceEvenly,
          crossAxisAlignment: WrapCrossAlignment.center,
          runAlignment: WrapAlignment.spaceAround,
          runSpacing: w / 20,
          children: [
            bannerCard(
              size.width - ((size.width - w * columnInt) / (columnInt + 1) * 3),
            ),
          ],
        ),
        Container(height: w / 20),
        ...characterWrapsList,
        Container(height: w / 20),
      ],
    );
    return list;
  }

  Widget bannerCard(double w) {
    return Card(
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      child: Image.file(
        File(_img),
        width: w,
        height: w / 3,
        fit: BoxFit.cover,
      ),
    );
  }

  List<Widget> characterWraps(double w, int columnInt) {
    var characterWraps = <Widget>[];
    var characterWidgets = characterCards(w);
    var tempArr = <Widget>[];
    var tempCount = 0;
    pushWrap() {
      if (tempCount > 0) {
        characterWraps.add(Wrap(
          alignment: WrapAlignment.spaceEvenly,
          crossAxisAlignment: WrapCrossAlignment.center,
          runAlignment: WrapAlignment.spaceAround,
          children: tempArr,
        ));
        characterWraps.add(Container(height: w / 20));
        tempArr = [];
        tempCount = 0;
      }
    }

    for (var i = 0; i < characterWidgets.length; i++) {
      tempArr.add(characterWidgets[i]);
      if (++tempCount == columnInt) {
        pushWrap();
      }
    }
    pushWrap();
    return characterWraps;
  }

  List<Widget> characterCards(double w) {
    return characters.map((c) {
      return characterCard(c, w);
    }).toList();
  }

  Widget characterCard(Character c, double w) {
    Widget content = Column(
      children: [
        Stack(
          children: [
            Padding(
              padding: EdgeInsets.all(w / 15),
              child: LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  return Image.file(
                    File("$repo/pics/Character/${c.icon}.png"),
                    width: constraints.maxWidth,
                    height: constraints.maxWidth,
                  );
                },
              ),
            ),
            Align(
              alignment: Alignment.topLeft,
              child: Padding(
                padding: EdgeInsets.all(w / 30),
                child: Image.file(
                  File('$repo/pics/Csxylic/${c.element}.png'),
                  width: w / 6,
                ),
              ),
            ),
          ],
        ),
        Container(
          width: w,
          padding: EdgeInsets.only(top: w / 30, bottom: w / 25),
          color: const Color(0xffe9e5dd),
          child: SelectableText(
            "${c.name}\n",
            maxLines: 1,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontSize: w / 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
    Color cardColor;
    if (c.grade == 5) {
      cardColor = const Color(0xffffa95d);
    } else if (c.grade == 4) {
      cardColor = const Color(0xff4a88e3);
    } else {
      cardColor = const Color(0xffe78c96);
    }
    content = Container(
      decoration: BoxDecoration(
        color: cardColor,
      ),
      child: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            tileMode: TileMode.repeated,
            colors: [
              Color(0x55000000),
              Color(0x44000000),
              Color(0x33000000),
              Color(0x44000000),
              Color(0x55000000),
            ],
          ),
        ),
        child: content,
      ),
    );
    content = Card(
      color: Colors.transparent,
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      child: content,
    );
    content = GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CharacterDetailScreen(c),
          ),
        );
      },
      child: content,
    );
    content = SizedBox(
      width: w,
      child: content,
    );
    return content;
  }
}
